<?php

namespace Mlym\CodeGeneration\InitGeneration\Controller\Method;

use EasySwoole\EasySwoole\Trigger;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
use Mlym\CodeGeneration\ClassGeneration\MethodAbstract;

class WriteJson extends MethodAbstract
{

    function addMethodBody()
    {
        $method = $this->method;
        $method->setProtected();
        $method->addParameter('statusCode')->setDefaultValue(200);
        $method->addParameter('result')->setDefaultValue(null);
        $method->addParameter('msg')->setDefaultValue(null);
        $method->setReturnType('bool');
        $method->setBody(<<<BODY
if (!\$this->response()->isEndResponse()) {
    \$data = array(
        "code" => \$statusCode,
        "msg" => \$msg
    );
    empty(\$result) || \$data['data'] = \$result;
    \$this->response()->write(json_encode(\$data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    \$this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
    \$this->response()->withStatus(200);
    return true;
} else {
    return false;
}
BODY
        );
    }

    function getMethodName(): string
    {
        return 'writeJson';
    }

    public function addComment()
    {
        $comment = <<<COMMENT
输出Json
@param int \$statusCode 状态码
@param mixed \$result 响应结果
@param string \$msg 状态信息
@return bool
@throws \Throwable
COMMENT;
        $this->method->addComment($comment);
    }
}